<template>
  <div class="yy-page yy-schedule-manage">
    <div class="yy-schedule-manage_employee">
      <el-table
          :key="Math.random()"
          :data="table.data"
          :span-method="arraySpanMethod"
          row-key="_id"
          border
          lazy
          :load="onLoadItemMember"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <template v-for="column in table.columns" :key="column.field">
          <el-table-column
              v-if="column.showable && ((!column.condition && column != false) || column.condition(column))"
              :type="column.type"
              :property="column.field"
              :label="typeOf(column.label) == 'function' ? column.label() : column.label"
              :render-header="column.renderHeader"
              :width="column.width"
              :min-width="column.minWidth || 120"
              :align="column.align"
              :fixed="column.fixed || false"
              :sortable="column.sortable"
          >
            <template #default="scope" v-if=" !['index','name','categoryName', 'deptName'].includes(column.field)">
              <div v-if="scope.row._id.startsWith('employee_')">
                <el-select  v-model="scope.row[column.field]" placeholder="请选择时段" style="width: 100%;" @change="onSaveSchedule(scope.row)">
                  <el-option :label="op.label" :value="op.value" v-for="op in clinicHoursArr" :key="op.value"/>
                </el-select>
              </div>
              <div v-else>
                <span :style="scope.row[column.field] == 0 ? 'color: #ccc;' : ''">{{clinicHoursArr.find(item => item.value === scope.row[column.field])?.label}}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <div class="yy-page-paging">
        <el-pagination small background layout="prev, pager, next, total" :total="table.paging.total"
                       v-model:current-page="table.paging.pageIndex"
                       v-model:page-size="table.paging.pageSize"
                       @current-change="table.paging.pageChange"
        />
      </div>
    </div>
    <div class="yy-schedule-manage_footer">

    </div>
  </div>
</template>
<script setup lang="ts">
import {nextTick, onBeforeMount, reactive, ref} from "vue";
import RegItemApi from "@/api/queue/RegItemApi";
import {changeListToTree, typeOf, formatDate} from "@/utils/yayi";
import {TableColumn} from "@/model/Definition";
import ScheduleApi from "@/api/queue/ScheduleApi";
import {QueueScheduleModel} from "@/model/QueueScheduleModel";
import {QueueItemEmplModel} from "@/model/QueueItemEmplModel";
import SystemApi from "@/api/system/system";
import {ElMessage} from "element-plus";

const clinicHoursArr: {label: string, value: number}[] = [
  {label: '休息', value: 0}, {label:'上午', value: 1}, {label: '下午', value: 3}, {label: '全天', value: 5}
]

const table = reactive<{
  isLoading: boolean,
  paging?: any,
  columns: TableColumn[],
  data: QueueScheduleModel[],
  formats?: any
}>({
  isLoading: false,
  paging: {
    isPaging: true,
    pageSize: 30,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      listAllItem(pageIndex);
    }
  },
  columns: [
    {
      "field":"name",
      "label":"名称",
      "showable":true,
      fixed: 'left',
      width: 200
    },
    {
      "field":"deptName",
      "label":"科室",
      "showable":true,
      fixed: 'left'
    },
    {
      "field":"categoryName",
      "label":"挂号类目",
      "showable":true,
      fixed: 'left'
    }
  ],
  data: []
})

const dateList = ref([])

onBeforeMount(() => {
  generateNextDay()
})

// 从今天开始获取近一周的日期和星期
const generateNextDay = () => {
  SystemApi.getServerTime().then((res: any) => {
    const currentDateTime = new Date(res.serverTime)
    let dates = [];
    let today = currentDateTime;
    for (let i = 0; i < 14; i++) {
      let date = new Date(today);
      date.setDate(today.getDate() + i);
      let dayName = date.toLocaleDateString(undefined, { weekday: 'short' }); // 星期几
      dates.push({date, day: dayName});
    }
    dateList.value = dates
    table.columns.push(...dates.map(item => {
      return Object.assign({
        "field": formatDate(item.date, 'YYYY-MM-DD'),
        "label": formatDate(item.date, 'MM月DD日'),
        "align": "center",
        "showable":true
      })
    }))

    listAllItem()
  })
}

const arraySpanMethod = ({ row, column, rowIndex,  columnIndex,  }: any) => {
  if (!row._id.startsWith('employee_')) {
    if (columnIndex === 1) {
      return [1, 1]
    } else if (columnIndex === 1) {
      return [0, 0]
    }
  }
}


const listAllItem = (pageIndex = 1) => {
  RegItemApi.listRegItem(pageIndex, table.paging.pageSize).then(pagingData => {
    table.data = pagingData.data.map(child => Object.assign({}, child, {_id: 'item_' + child.id + 'dept_' + child.deptId, deptId: child.deptId, itemId: child.id, children: [], hasChildren: []}))
    table.paging = Object.assign({}, table.paging, {
      pageIndex: pagingData.pageIndex,
      total: pagingData.total
    })
  })
}


const onLoadItemMember = (row, treeNode: unknown,  resolve:any) => {

  Promise.all([RegItemApi.selectItemEmployeeByDeptId(row.deptId, row.id), ScheduleApi.listScheduleByDeptId(row.deptId, row.id)]).then(result => {
    const itemEmployees = result[0]
    const itemSchedules = result[1]

    const employees = []

    const dateFieldObj = {}
    dateList.value.forEach(item => {
      dateFieldObj[formatDate(item.date, 'YYYY-MM-DD')] = 0
    })

    itemEmployees.forEach(empl=> {
      const data = Object.assign({}, {
        id: empl.emplId,
        name: empl.emplName + `(${empl.emplCode})`,
        categoryName: empl.categoryName,
        categoryId: empl.categoryId,
        code: empl.emplCode,
        deptId: row.deptId,
        itemId: row.itemId,
        _name: empl.emplName,
        _id: "employee_" + empl.id,
        _backArr: {},
        _scheduleIds: {},
      }, dateFieldObj)
      const schedules: QueueScheduleModel[] = itemSchedules.filter(item => item.itemId === row.id && item.doctorId === data.id && item.categoryId === data.categoryId)
      for (let schedule of schedules) {
        data[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.clinicHoursId
        data._backArr[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.clinicHoursId
        data._scheduleIds[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.id
      }
      employees.push(data)
    })

    row.children = employees
    resolve(employees)

  })
}

const onSaveSchedule = (empl) => {
  const schedules = [];
  dateList.value.forEach(data => {
    if (!(empl._backArr[formatDate(data.date, 'YYYY-MM-DD')] === undefined && empl[formatDate(data.date, 'YYYY-MM-DD')] ==0) && empl[formatDate(data.date, 'YYYY-MM-DD')] != empl._backArr[formatDate(data.date, 'YYYY-MM-DD')]) {
      const schedule = new QueueScheduleModel().deserialize({
        id: empl._scheduleIds[formatDate(data.date, 'YYYY-MM-DD')] || undefined,
        departId: empl.deptId,
        itemId: empl.itemId,
        doctorId: empl.id,
        categoryId: empl.categoryId,
        scheduleDate: formatDate(data.date, 'YYYY-MM-DD'),
        clinicHoursId: empl[formatDate(data.date, 'YYYY-MM-DD')]
      })
      schedules.push(schedule)
    }
  })
  if(schedules?.length) {
    ScheduleApi.saveEmployeeSchedule(schedules).then((result) => {
      if (result?.length) {
        result.forEach(schedule => {
          // 更新当前科室排班计划列表
          empl[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.clinicHoursId
          empl._backArr[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.clinicHoursId
          empl._scheduleIds[formatDate(schedule.scheduleDate, 'YYYY-MM-DD')] = schedule.id
        })
      }
      ElMessage.success("计划保存成功")
    })
  }
}

</script>
<style scoped lang="scss">
.yy-schedule-manage {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}
</style>